package com.lxq.live.service;

import com.lxq.live.dao.RedisVerificationCode;
import com.lxq.live.pojo.NewResetEnum;
import com.lxq.live.pojo.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class ResetPasswordService {

    @Autowired
    LiveMailService liveMailService;
    @Autowired
    RedisVerificationCode redisVerificationCode;

    public NewResetEnum newResetRequest(String userId, String mail){
        var verificationCode=redisVerificationCode.isExist(userId);
        var executed=false;
        if (verificationCode==null){
            verificationCode=new VerificationCode();
            verificationCode.setUserId(userId);
            executed=redisVerificationCode.create(verificationCode);
            if (!executed)return NewResetEnum.WRONG;
        }
        if(verificationCode.getLeftOvers()<=0){
            return NewResetEnum.FORBID;
        }
        var freedomCode=generateVerificationCode();
        liveMailService.sendSimpleMail("重置密码",mail,"你本次的验证码是："+freedomCode+
                "，10分钟内有效。");
        verificationCode.leftOversDown();
        verificationCode.setLatestCode(freedomCode);
        executed=redisVerificationCode.update(verificationCode);
        return executed? NewResetEnum.PASS: NewResetEnum.WRONG;
    }

    private String generateVerificationCode(){
        var random=new Random();
        return random.nextInt(900000)+100000+"";
    }
}
